package org.learning;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.stream.IntStream;

/**
 * CyclicBarrier使用案例演示
 * 多位候选人参加面试的案例模拟。面试分两轮，每轮都要人到齐了才能开始，并且都结束了才能进行下一轮
 * 从家出发到达公司 -》 笔试到答题结束 -》 面试到面试结束。
 */
public class A_23 {
    static class CandidateThread extends Thread {
        private final CyclicBarrier cyclicBarrier;
        private final Random random = new Random();

        public CandidateThread(String name, CyclicBarrier cyclicBarrier) {
            super(name);
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            try {
                String name = Thread.currentThread().getName();
                System.out.println(name + "从家里出发。。。");
                Thread.sleep(random.nextInt(10000));
                System.out.println(name + "到达面试公司。。。");
                cyclicBarrier.await();

                System.out.println(name + "开始笔试。。。");
                Thread.sleep(random.nextInt(10000));
                System.out.println(name + "笔试结束。。。");
                cyclicBarrier.await();

                System.out.println(name + "开始面试。。。");
                Thread.sleep(random.nextInt(10000));
                System.out.println(name + "面试结束。。。");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (BrokenBarrierException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5, () -> System.out.println("该阶段结束"));
        IntStream
                .rangeClosed(1, 5)
                .mapToObj(v -> new CandidateThread("候选人" + v, cyclicBarrier))
                .forEach(Thread::start);

    }
}
